<?php

namespace app\admin\controller\xiservice;

use app\common\controller\Backend;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Exception;
use think\Db;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\common\model\xiservice\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\xiservice\Order;
        $this->view->assign("choseTypeList", $this->model->getChoseTypeList());
        $this->view->assign("visitPayStatusList", $this->model->getVisitPayStatusList());
        $this->view->assign("bargainList", $this->model->getBargainList());
        $this->view->assign("notifyList", $this->model->getNotifyList());
        $this->view->assign("getgenhuanlist", $this->model->getgenhuanlist());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['user', 'worker', 'service'])
                ->where($where)
                ->where('order_type',10)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'order_no', 'user_id', 'worker_id', 'unusual', 'service_id', 'pay_type', 'pay_time', 'pay_status', 'transaction_id', 'servicenums', 'total_money', 'visit_money', 'pay_money', 'reserve_date', 'service_start_time', 'service_duration', 'order_status', 'addr', 'addr_detail', 'createtime', 'province_id', 'city_id', 'area_id','task_mode','check_images','construction_images','tax_email','tax_title','tax_no','fwpc','fwsj','service_desc_images']);
                $row->visible(['user']);
                $row->getRelation('user')->visible(['username', 'mobile']);
                $row->visible(['worker']);
                $row->getRelation('worker')->visible(['contact_name', 'mobile','desc']);
                $row->visible(['service']);
                $row->getRelation('service')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());
            // echo "<pre>";
            // print_r($result);die;
            return json($result);
        }
        return $this->view->fetch();
    }


    

    /**
     * 订单详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->with(['user', 'worker', 'service'])->where('order.id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }


        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /*
    ** 取消订单
     */
    public function cancel($ids = null)
    {
        $row = $this->model->with(['user', 'worker', 'service'])->where('order.id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['order_status'] > 30) {
            $this->error('订单状态错误');
        }
        $res = $this->model->changeOrderStatus($ids, 'cancel');
        if (!$res['status']) {
            $this->error($res['msg']);
        }

        $result = ["code" => 1, "data" => [], "msg" => '操作成功', 'url' => ''];
        return json($result);
    }


    /*
    ** 确认接单
     */
    public function sure($ids = null)
    {
        $row = $this->model->with(['user', 'worker', 'service'])->where('order.id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['order_status'] > 30) {
            $this->error('订单状态错误');
        }
        $res = $this->model->changeOrderStatus($ids, 'confirm');
        if (!$res['status']) {
            $this->error($res['msg']);
        }
        $result = ["code" => 1, "data" => [], "msg" => '操作成功', 'url' => ''];
        return json($result);
    }

    /*
    ** 开始服务
     */
    public function start($ids = null)
    {
        $row = $this->model->with(['user', 'worker', 'service'])->where('order.id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['order_status'] != 30) {
            $this->error('订单状态错误');
        }
        $res = $this->model->changeOrderStatus($ids, 'service');
        if (!$res['status']) {
            $this->error($res['msg']);
        }
        $result = ["code" => 1, "data" => [], "msg" => '操作成功', 'url' => ''];
        return json($result);
    }

    /*
    ** 完成服务
     */
    public function finish($ids = null)
    {
        $row = $this->model->with(['user', 'worker', 'service'])->where('order.id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['order_status'] != 40) {
            $this->error('订单状态错误');
        }
//        $res = $this->model->changeOrderStatus($ids,'finished');
        $res = $this->model->changeOrderStatus($ids, 'quality');
        if (!$res['status']) {
            $this->error($res['msg']);
        }
        $result = ["code" => 1, "data" => [], "msg" => '操作成功', 'url' => ''];
        return json($result);
    }


    /*
    ** 退款
     */
    public function refund($ids = null)
    {
        $row = $this->model->with(['user', 'worker', 'service'])->where('order.id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['order_status'] != 40) {
            $this->error('订单状态错误');
        }
        $res = $this->model->changeOrderStatus($ids, 'refund');
        if (!$res['status']) {
            $this->error($res['msg']);
        }
        $result = ["code" => 1, "data" => [], "msg" => '操作成功', 'url' => ''];
        return json($result);
    }

    /**
     * 派单/更换服务人员
     */

     public function changeworker($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    // public function changeworker($ids = null)
    // {
    //     $row = $this->model->with(['user', 'worker', 'service'])->where('order.id', $ids)->find();
    //     if (!$row) {
    //         $this->error(__('No Results were found'));
    //     }
    //     if ($this->request->isPost()) {
    //         $params = $this->request->post("row/a");
    //         if ($params) {
    //             $params = $this->preExcludeFields($params);
    //             $result = false;
    //             $scheduleModel = new \app\common\model\xiservice\Schedule;

    //             $userModel = new \app\common\model\xiservice\User;
    //             $user = $userModel->where('id', $params['worker_id'])->find();
    //             $params['worker_id'] = $user['user_id'];
    //             Db::startTrans();
    //             try {
    //                 //是否采用模型验证
    //                 if ($this->modelValidate) {
    //                     $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
    //                     $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
    //                     $row->validateFailException(true)->validate($validate);
    //                 }
    //                 //更新原服务人员的时间表
    //                 $ret = $scheduleModel->where('order_id', $ids)->delete();
    //                 //更新服务人员时间表
    //                 if ($params['worker_id'] > 0) {
    //                     $req = $scheduleModel->orderSchedule($params['worker_id'], $ids, $row['service_start_time'], $row['service_duration']);
    //                 }
    //                 //更新服务人员
    //                 $result = $row->allowField(true)->save($params);
    //                 Db::commit();
    //             } catch (ValidateException $e) {
    //                 Db::rollback();
    //                 $this->error($e->getMessage());
    //             } catch (PDOException $e) {
    //                 Db::rollback();
    //                 $this->error($e->getMessage());
    //             } catch (Exception $e) {
    //                 Db::rollback();
    //                 $this->error($e->getMessage());
    //             }
    //             if ($result !== false) {
    //                 $this->success();
    //             } else {
    //                 $this->error(__('No rows were updated'));
    //             }
    //         }
    //         $this->error(__('Parameter %s can not be empty', ''));
    //     }
    //     $this->view->assign("row", $row);
    //     $this->view->assign("id", $ids);
    //     return $this->view->fetch();
    // }


    // public function genhuan($ids=null)
    // {

    //     $row = $this->model->get($ids);
        

    //     $rows = $row['id'];
       
    //     if (!$row) {
    //         $this->error(__('No Results were found'));
    //     }
    //         $params = $this->request->post("row/a");
    //         // echo "<pre>";
    //         // print_r($params);die;
    //         $res = Db::name('xiservice_user_quote')->where('order_id',$rows)->update($params);
    //         if($res){
    //             $this->success(_('更换成功')); 
    //         }else{
    //             $this->error(__('更换失败'));   
    //         }
           
  
    //     $this->view->assign("row", $row);
    //     return $this->view->fetch();
    // } 

    /**
     * 公示订单
     */
    public function open($ids = null)
    {
        $row = $this->model->with(['user', 'worker', 'service'])->where('order.id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['order_status'] > 21) {
            $this->error('订单状态错误');
        }
        $res = $this->model->changeOrderStatus($ids, 'open');
        if (!$res['status']) {
            $this->error($res['msg']);
        }
        $result = ["code" => 1, "data" => [], "msg" => '操作成功', 'url' => ''];
        return json($result);
    }
}
